from sklearn import metrics
import  matplotlib.pyplot as plt
import numpy as np

def evaluate(pre_value,y_true,target_name=None,labels=None):
    report = metrics.classification_report(y_true,pre_value,target_names=target_name,labels=labels)
    confuse_matrix = metrics.confusion_matrix(y_true, pre_value)
    return report,confuse_matrix

def save_report(report,path):
    with open(path,'w') as f:
        f.write(report)

# 混淆矩阵可视化
def plot_matrix(confuse, title=None, thresh=0.8, axis_labels=None):
    confuse = confuse.astype('float') / confuse.sum(axis=1)[:, np.newaxis]  # 归一化

# 画图，如果希望改变颜色风格，可以改变此部分的cmap=plt.get_cmap('Blues')处
    plt.imshow(confuse, interpolation='nearest', cmap=plt.get_cmap('Blues'))
    plt.colorbar()  # 绘制图例

# 图像标题
    if title is not None:
        plt.title(title)
# 绘制坐标
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

# 显示
    plt.show()

def fault_cls(labels,pre_values):
    # 返回其中错误类别的混淆矩阵
    tn = [] # 标签中错误的
    pn = [] # 预测中错误的
    for label,pre in zip(labels,pre_values):
        if label!=pre:
            tn.append(label)
            pn.append(pre)
    _,faulse_cm = evaluate(pn,tn)
    true_cls = faulse_cm.sum(axis=1)==0 # 其中个别分类正确的类
    faulse_cm[true_cls,true_cls] = 1

    return faulse_cm